package com.gitee.feizns.quickstart.web.converter;

import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.NonNull;

import java.util.function.BiPredicate;

/**
 * 字符串转枚举实现类
 * @see Converter
 * @param <T>
 */
public class StringToEnumConverter<T extends Enum<?>> implements Converter<String, T> {

    /**
     * 目标枚举类型
     */
    private final Class<T> targetEnumType;

    /**
     * 是否是目标枚举规则
     */
    private final BiPredicate<String, T> predicate;

    public StringToEnumConverter(Class<T> targetEnumType, BiPredicate<String, T> predicate) {
        this.targetEnumType = targetEnumType;
        this.predicate = predicate;
    }

    @Override
    public T convert(@NonNull String source) {
        T[] constants = targetEnumType.getEnumConstants();
        for (T constant : constants) {
            if ( predicate.test(source, constant) )
                return constant;
        }
        return null;
    }

}